﻿using Common.Framework.Core.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Framework.Core.Attribute
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
    public class ModelValidationAttribute : ActionFilterAttribute
    {
        /// <summary>
        ///  控制器中的操作执行之前调用此方法
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var modelState = context.ModelState;
            if (!modelState.IsValid)
            {
                string error = string.Empty;
                foreach (var key in modelState.Keys)
                {
                    var state = modelState[key];
                    if (state.Errors.Any())
                    {
                        var errorInfo = state.Errors.First();
                        string ex = (errorInfo.Exception == null ? "" : errorInfo.Exception.ToString());
                        error = string.IsNullOrEmpty(errorInfo.ErrorMessage) ? ex : errorInfo.ErrorMessage;
                        break;
                    }
                }

                ServiceResult result = new ServiceResult
                {
                    Code = StatusCodes.Status403Forbidden, //这里使用403,目的是为了让前端进行特殊处理.
                    Msg = error
                };

                var jsonResult = new JsonResult(result);
                context.Result = jsonResult;
            }
        }
    }
}
